package com.chenfan.filestore.job;

import cn.hutool.core.util.NumberUtil;
import com.chenfan.filestore.model.Task;
import com.chenfan.filestore.model.dto.ParseExcelDTO;
import com.chenfan.filestore.service.FileService;
import com.chenfan.filestore.service.TaskService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author K
 * @date 2023/7/27 10:16 AM
 */
@Slf4j
@Component
public class TaskCleanerJob {

    @Autowired
    private TaskService taskService;
    @Autowired
    private FileService fileService;

    @XxlJob("taskCleaner")
    public ReturnT<String> taskCleaner(String param) {
        Integer expireDays = NumberUtil.isInteger(param) ? Integer.valueOf(param) : 30;
        // 查询出对应的数据
        List<Task> tasks = taskService.listByExpireDays(expireDays);
        // 做逻辑处理
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        ExecutorCompletionService<Boolean> executorCompletionService = new ExecutorCompletionService<>(executorService);
        tasks.forEach(e -> executorCompletionService.submit(new CleanFileJob(fileService, taskService, e)));

        tasks.forEach(e -> {
            try {
                executorCompletionService.take().get();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
            }
        });
        return ReturnT.SUCCESS;
    }



}
class CleanFileJob implements Callable<Boolean> {

    private FileService fileService;
    private TaskService taskService;
    private Task task;

    public CleanFileJob (FileService fileService, TaskService taskService, Task task) {
        this.fileService = fileService;
        this.taskService = taskService;
        this.task = task;
    }

    @Override
    public Boolean call() {
        try {
            fileService.removeFiles(task.getFailedFileUrl(), task.getDownFileUrl());
            task.setIsDelete(1);
            taskService.updateById(task);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
